﻿using DeepZoom;
using OpenSlideNET;
using System;
using System.IO;
using System.Xml.Linq;

namespace VirtualSlideViewer.TileSources
{
    class OpenSlideTileSource : DeepZoomImageTileSource, IDisposable
    {
        private OpenSlideImage _image;
        private DeepZoomGenerator _generator;


        public OpenSlideTileSource(string path)
        {
            _image = OpenSlideImage.Open(path);
            _generator = new DeepZoomGenerator(_image);
            UriSource = new Uri(path);
        }

        protected override XElement LoadDziXml()
        {
            return XElement.Parse(_generator.GetDzi());
        }

        public override object GetTileLayers(int tileLevel, int tilePositionX, int tilePositionY)
        {
            var ms = new MemoryStream();
            _generator.GetTileAsJpegToStream(tileLevel, tilePositionX, tilePositionY, ms);
            ms.Position = 0;
            return ms;
        }

        public void Dispose()
        {
            _image.Dispose();
            _generator.Dispose();
        }
    }
}
